package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.service.UserInfoService;
import com.etc.service.impl.UserInfoServiceImpl;
import com.etc.util.AesLoUtil;
import com.etc.util.DESDemo;
import com.fasterxml.jackson.databind.ObjectMapper;

/**用于注册
 * Servlet implementation class RegisterServlet
 * @author nxlnian
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserInfoService userInfoService = new UserInfoServiceImpl();

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = request.getParameter("op");
		if("user".equals(op)) {
			try {
				Register(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if ("findMobile".equals(op)) {
			findMobile(request,response);
		}
		
		
	}

	private void findMobile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 接收请求参数
		String mobile = request.getParameter("mobile");
		// 调用业务层 返回值大于0成功
		int findMobile = userInfoService.findMobile(mobile);
		// 响应
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(findMobile);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(json);		
	}

	private void Register(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 接收请求参数
		String userName = request.getParameter("userName");
		String mobile = request.getParameter("mobile");
		String password = AesLoUtil.Decrypt(request.getParameter("password"));//前端解密
		password = DESDemo.encrypt(password);//后端加密
		// 调用业务层 返回值大于0成功
		String qq = userInfoService.adduser(userName, password, mobile);
		// 响应
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(qq);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(json);
		
	}

}
